/**
 * 版权所有：厦门市巨龙信息科技有限公司
 * Copyright 2023 Xiamen Dragoninfo Eng. Co. Ltd.
 * All right reserved.
 */
package com.github.alfred.tool.impl;

import com.github.alfred.tool.RateLimiter;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 类说明
 *
 * @author chengh
 * @date 2023/11/7 20:08
 */
@Service
public class RedissonRateLimiter implements RateLimiter {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public RRateLimiter getRedissonRateLimiter(String key, int timeout, TimeUnit unit, int rate) {
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        //如果限流器不存在，就创建一个RRateLimiter限流器
        if (!rateLimiter.isExists()) {
            rateLimiter.trySetRate(RateType.OVERALL, rate, timeout, RateIntervalUnit.valueOf(unit.name()));
            return rateLimiter;
        }
        //获取限流的配置信息
        RateLimiterConfig rateLimiterConfig = rateLimiter.getConfig();
        //上次配置的限流时间毫秒值
        Long rateInterval = rateLimiterConfig.getRateInterval();
        //上次配置的限流次数
        Long count = rateLimiterConfig.getRate();
        //将timeOut转换成毫秒之后再跟rateInterval进行比较
        if (TimeUnit.MILLISECONDS.convert(timeout, unit) != rateInterval || count != rate) {
            //如果rateLimiterConfig的配置跟我们注解上面的值不一致，说明服务器重启过，程序员又修改了限流的配置
            //删除原有配置
            rateLimiter.delete();
            //以程序员重启后的限流配置为准，重新设置
            rateLimiter.trySetRate(RateType.OVERALL, count, timeout, RateIntervalUnit.valueOf(unit.name()));
        }
        return rateLimiter;
    }
}
